package com.cml.framework.component.sign;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cml.framework.component.token.UUIDTokenGenerator;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtils {

    public static String sign(String secret, String subject, long expire) {
        try {
            Algorithm algorithmHS = Algorithm.HMAC256(secret);
            String token = JWT.create().withSubject(subject).withExpiresAt(new Date(expire)).sign(algorithmHS);
            return token;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String verify(String key, String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(key);
            JWTVerifier verifier = JWT.require(algorithm).build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
